/*
 使用方式
 var msjstation=new p3D();
 msjstation.initmsj3D('divid',{...},[datajson]);
 msjstation.start();
 */
 function p3D() { }
 var p3DObj = null;
 p3D.prototype.start = function () {
     //此处用于判断浏览器

     //开始
     var _this = this;
     p3DObj = _this;
     _this.initThree(_this.fId);
     _this.initCamera();
     _this.initScene();
     _this.initHelpGrid();
     _this.initLight();
     //_this.addTestObj();
     //添加3D对象
     $.each(_this.objList, function (index,_obj) {
         _this.InitAddObject(_obj);
     });
     // _this.InitModelsObject();
     _this.materialController = new LR.MaterialController(); // 初始化切换材质
     // _this.initRayControls();

     //
     // var geometry = new THREE.BoxGeometry( 1, 1, 1 );
     // var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
     // var cube = new THREE.Mesh( geometry, material );
     // this.scene.add( cube );
     //
     // geometry = new THREE.PlaneGeometry( 10, 10, 32 );
     // material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
     // var plane = new THREE.Mesh( geometry, material );
     //
     // var vmatrix=[2.811701,0.866545,-0.586034,0,-0.934714,3.744297,1.051926,0,1.294095,-1.004136,4.72409,0,1.437113,0.627707,2.564652,1];
     // var matrix = new THREE.Matrix4();
     // matrix.fromArray( vmatrix );
     // plane.applyMatrix(matrix);
     // //plane.matrix.fromArray( vmatrix );
     // //plane.matrix.decompose( plane.position, plane.quaternion, plane.scale );
     // this.scene.add( plane );

     // var vpos = new THREE.Vector3( 10, 1, 10 );
     // var geometry = new THREE.SphereBufferGeometry(10.5);
     // var material = new THREE.MeshBasicMaterial({color: 0xff0000});
     // var sphereInter = new THREE.Mesh(geometry, material);
     // sphereInter.position.copy(vpos);
     // //this.scene.add(sphereInter);
     //
     // //var vpos2 = vpos.clone();
     // //vpos2.applyAxisAngle ( new THREE.Vector3( 1, 0, 0 ),  1.570796326);
     // //vpos2.applyAxisAngle ( new THREE.Vector3( 0, 1, 0 ),  1.570796326);
     // var phi=parseFloat(this.camera.rotation.y);
     // var theta=parseFloat(this.camera.rotation.x);
     // var targetPosition =this.camera.position.clone();
     // targetPosition.x = this.camera.position.x + 100 * Math.sin(phi) * Math.cos(theta);
     // targetPosition.y = this.camera.position.y + 100 * Math.cos(phi);
     // targetPosition.z = this.camera.position.z + 100 * Math.sin(phi) * Math.sin(theta);
     //
     // var sphereInter2 = new THREE.Mesh(geometry, material);
     // sphereInter2.position.copy(targetPosition);
     // this.scene.add(sphereInter2);
     //

     _this.initMouseCtrl();
     //创建按钮
     _this.addBtns(_this.btns);

     _this.animation();

	 //allen
	 window.addEventListener( 'resize', _this.onWindowResize, false );

 }
 /*
 方法：初始化
 fid 画布所属div的Id
 option:参数 {
             antialias:true,//抗锯齿效果为设置有效
             clearCoolr:0xFFFFFF,
             showHelpGrid:false,//是否显示网格线
                 }
 */
 p3D.prototype.initp3D = function (_fId, _option,_datajson) {
     //参数处理
     this.option = new Object();
     this.option.antialias = _option.antialias || true;//刷新色
     this.option.clearCoolr = _option.clearCoolr || 0x1b7ace;//刷新色
     this.option.showHelpGrid = _option.showHelpGrid || false;//刷新色
     //对象
     this.fId = _fId;
     //this.width = $("#" + _fId).width();
     //this.height = $("#" + _fId).height();
     this.width = window.innerWidth;
     this.height = window.innerHeight;
     this.renderer = null;//渲染器
     this.camera = null;//摄像机
     this.scene = null;//场景
     this.SELECTED=null;
     this.objects = [];
     this.mouseClick = new THREE.Vector2();
     this.raycaster = new THREE.Raycaster();
     this.controls = null;//鼠标控制器
     this.objList = _datajson.objects;//对象列表
     this.eventList = _datajson.events;//事件对象列表
     this.btns = _datajson.btns;//按钮列表
     var _this = this;
 }
 //初始化渲染器
 p3D.prototype.initThree = function () {
     var _this = this;
     _this.renderer = new THREE.WebGLRenderer({ alpha: true, antialias: _this.option.antialias });
     _this.renderer.setSize(_this.width, _this.height);
     $("#" + _this.fId).append(_this.renderer.domElement);
     _this.renderer.setClearColor(_this.option.clearCoolr, 1.0);
     _this.renderer.shadowMap.enabled = true;//
     _this.renderer.shadowMapSoft = true;
     //事件
     _this.renderer.domElement.addEventListener('mousedown', _this.onDocumentMouseDown, false);
     _this.renderer.domElement.addEventListener('mousemove', _this.onDocumentMouseMove, false);
 }
 //初始化摄像机
 p3D.prototype.initCamera = function () {
     var _this = this;
     _this.camera = new THREE.PerspectiveCamera(45, _this.width / _this.height, 1, 100000);
     _this.camera.name = 'mainCamera';
     _this.camera.position.x =0;
     // _this.camera.position.y =1000;
     // _this.camera.position.z =-1800;
     _this.camera.position.y =200;
     _this.camera.position.z =300;
     _this.camera.up.x = 0;
     _this.camera.up.y = 1;
     _this.camera.up.z = 0;
     _this.camera.lookAt({ x: 0, y: 0, z: 0 });
     _this.objects.push(_this.camera);
 }
 //创建场景
 p3D.prototype.initScene=function() {
     var _this = this;
     _this.scene = new THREE.Scene();
 }
 //添加对象
 p3D.prototype.addObject = function (_obj) {
     var _this = p3DObj;
     _this.objects.push(_obj);
     _this.scene.add(_obj);
 }
  //删除对象
 p3D.prototype.delObject = function (_objname,_deltype) {
     var _this = p3DObj;
     //_this.objects.remove(_obj);
	 for ( var i = 0; i < _this.objects.length; i ++ ) {
		 var _obj=_this.objects[i];
		 if (_obj.name != null && _obj.name != '') {
			 if (_obj.name == _objname) {
				 _this.scene.remove(_obj);
				 _this.objects.splice(i,1);
				 i--;
				 if(false==_deltype)
					return true;
			 }
		 }
	 }
	 /*
	 $.each(_this.objects, function (index,_obj) {
		 if (_obj.name != null && _obj.name != '') {
			 if (_obj.name == _objname) {
				 _this.scene.remove(_obj);
				 _this.objects.splice(index,1);
				 return true;
			 }
		 }
	 });
	 */
	 return false;
 }
  //show hide对象
 p3D.prototype.showObject = function (_objname,_visable,_deltype) {
     var _this = p3DObj;
     //_this.objects.remove(_obj);
	 for ( var i = 0; i < _this.objects.length; i ++ ) {
		 var _obj=_this.objects[i];
		 if (_obj.name != null && _obj.name != '') {
			 if (_obj.name.indexOf(_objname) >= 0) {
				 _obj.visible=_visable;
				 if(false==_deltype)
					return true;
			 }
		 }
	 }
	 return false;
 }
  //opacity对象
 p3D.prototype.showObjectOpacity = function (_objname,_opacity,_deltype) {
     var _this = p3DObj;
     //_this.objects.remove(_obj);
	 for ( var i = 0; i < _this.objects.length; i ++ ) {
		 var _obj=_this.objects[i];
		 if (_obj.name != null && _obj.name != '') {
			 if (_obj.name.indexOf(_objname) >= 0) {


				 if (_obj.material != null && typeof (_obj.material) != 'undefined') {
					 for(var m=0;m<_obj.material.length;m++) {
						_obj.material[m].opacity=_opacity;
					 }
				 }


				 if(false==_deltype)
					return true;
			 }
		 }
	 }
	 return false;
 }
 //创建网格线
 p3D.prototype.initHelpGrid = function () {
     var _this = this;
     if (_this.option.showHelpGrid) {
         var helpGrid = new THREE.GridHelper(1000, 50);
         _this.scene.add(helpGrid);
     }
 }
 //灯光布置
 p3D.prototype.initLight = function () {
     /*
     AmbientLight: 环境光，基础光源，它的颜色会被加载到整个场景和所有对象的当前颜色上。
	 PointLight：点光源，朝着所有方向都发射光线
	 SpotLight ：聚光灯光源：类型台灯，天花板上的吊灯，手电筒等
	 DirectionalLight：方向光，又称无限光，从这个发出的光源可以看做是平行光.
     */
     var _this = this;
     var light = new THREE.AmbientLight(0xcccccc);
     light.position.set(0, 0,0);
     _this.scene.add(light);
     var light2 = new THREE.PointLight(0x555555);
     light2.shadow.camera.near =1;
     light2.shadow.camera.far = 5000;
     light2.position.set(0, 350, 0);
     light2.castShadow = false;//表示这个光是可以产生阴影的
     _this.scene.add(light2);

 }
 //创建鼠标控制器
 p3D.prototype.initMouseCtrl=function() {
     var _this = this;
     //_this.controls = new THREE.OrbitControls(_this.camera);
     _this.controls = new THREE.OrbitControls(_this.camera, this.renderer.domElement);
     _this.controls.minDistance = 10;
     //controls.maxDistance = 500;
     _this.controls.addEventListener('change', _this.updateControls);
 }
 //控制器回调
 p3D.prototype.updateControls = function () {

    //controls.update();
 }
 //循环渲染界面
 p3D.prototype.animation = function () {
     var _this = p3DObj;
     if (TWEEN != null && typeof (TWEEN) != 'undefined') {
         TWEEN.update();
     }
	 _this.onUpdateSence();

     requestAnimationFrame(_this.animation);
     _this.renderer.render(_this.scene, _this.camera);
 }
 p3D.prototype.onUpdateSence = function() {
	 var _this = p3DObj;
	 var vv=0.0;
	 if (_this.vcmaterial != null && typeof (_this.vcmaterial) != 'undefined') {
		 //_this.vcmaterial.map.offset.y += 0.01;
		_this.vcmaterial.map.offset.x += 0.002;
		vv=_this.vcmaterial.map.offset.x;
	 }

	 if (_this.nurbsmaterial != null && typeof (_this.nurbsmaterial) != 'undefined') {
		_this.nurbsmaterial.map.offset.y -= 0.012;
	 }

	 if (_this.pathTubeGeometry != null && typeof (_this.pathTubeGeometry) != 'undefined') {
			var vscale=1.0;
			var v1=20;
			var offset = 10;
			var splineCamera=_this.camera;
			var vpathTubeGeometry=_this.pathTubeGeometry;
			//var time = Date.now();
			//var looptime = 20 * 1000;
			//var t = ( time % looptime ) / looptime;
			var t = ( _this.dynamicPathTimer % 1 );

			var binormal = new THREE.Vector3();
			var normal = new THREE.Vector3();

			//console.log(t+'  '+ _this.dynamicPathTimer);
			var pos = vpathTubeGeometry.parameters.path.getPointAt( t );
			pos.y+=v1;
			pos.multiplyScalar( vscale );
/*
			// interpolation
			var segments = vpathTubeGeometry.tangents.length;
			var pickt = t * segments;
			var pick = Math.floor( pickt );
			var pickNext = ( pick + 1 ) % segments;

			binormal.subVectors( vpathTubeGeometry.binormals[ pickNext ], vpathTubeGeometry.binormals[ pick ] );
			binormal.multiplyScalar( pickt - pick ).add( vpathTubeGeometry.binormals[ pick ] );

			var dir = vpathTubeGeometry.parameters.path.getTangentAt( t );

			normal.copy( binormal ).cross( dir );

			// we move on a offset on its binormal

			pos.add( normal.clone().multiplyScalar( offset ) );
*/
			splineCamera.position.copy( pos );

			// using arclength for stablization in look ahead
			var vty=( t + 30 / vpathTubeGeometry.parameters.path.getLength() ) % 1;
			var lookAt = vpathTubeGeometry.parameters.path.getPointAt( vty ).multiplyScalar( vscale );
			lookAt.y+=v1;
			// camera orientation 2 - up orientation via normal

			//if ( ! params.lookAhead )  lookAt.copy( pos ).add( dir );
			splineCamera.matrix.lookAt( splineCamera.position, lookAt, normal );
			splineCamera.rotation.setFromRotationMatrix( splineCamera.matrix, splineCamera.rotation.order );
			//splineCamera.lookAt(lookAt);
			//splineCamera.rotation.x+=Math.PI/180*360;
			//splineCamera.rotation.set(0,-Math.PI/180*180,0);
			//console.log(normal.x+'  '+ normal.y+'  '+ normal.z);
			_this.dynamicPathTimer+=0.001;
			if(_this.dynamicPathTimer>1.0) _this.dynamicPathTimer=0.0;
	 }
}
 p3D.prototype.onWindowResize = function() {
	 var _this = p3DObj;
	_this.width = window.innerWidth;
    _this.height = window.innerHeight;

	_this.camera.aspect = window.innerWidth / window.innerHeight;
	_this.camera.updateProjectionMatrix();

	_this.renderer.setSize( window.innerWidth, window.innerHeight );
}

/*
设备模型定位
*/
p3D.prototype.cameraLocal = function(campos,objpos) {
    var vd=campos.distanceTo(objpos);
    var vMoveDis=40;//40 1.016	米(m)
    var vMpos= campos;
    //console.log(vd,vMoveDis,vMpos);
    var endcurve = new THREE.LineCurve3( objpos,campos );
    if(vd>vMoveDis) {
        var vPoints= endcurve.getPoints(vd);
        vMpos= vPoints[vMoveDis].clone();
        //console.log(vd,vMoveDis,vMpos);
    }

    this.camera.position.set( vMpos.x, vMpos.y, vMpos.z );
    this.camera.lookAt(objpos);
}

p3D.prototype.initRayControls = function () {
    var _this = this;

    // 添加射线
    var parameters = {
        domElement: this.renderer.domElement,
        objects: this.scene.children,
        enabledChangeMaterialColor: true,
        //enableDetection: this.modeController.enableDetection,
        enabledClick: true
    };
    var rayControls = new THREE.RayControls(this.camera, this.scene, parameters);
    rayControls.selectObjectsCallBack = function (mesh) {
        console.log("选中模型：", mesh);
        // 恢复mesh的透明
        //_this.materialController.restoreAllMeshOpacity(_this.Object3D);
        // 改变颜色
        var arr = [];
        if (mesh) {
            arr.push(mesh);
        }
        _this.materialController.clickChangeColor(arr, new THREE.Color(0xff0000));
    };
    return ;
}

p3D.prototype.InitModelsObject = function () {
    var url='models/project.json';
    var _this = this;

    this.requestJSON(url, function (data) {
        var objList = {};
        //var objModelList = [];
        for(var m=data.object.children.length-1;m>=0;m--) {
            var vobj=data.object.children[m];
            if(vobj.userData && vobj.userData.model) {

                objList[vobj.userData.model] = objList[vobj.userData.model] || [];
                objList[vobj.userData.model].push(vobj);
                data.object.children.splice(m, 1);

            }
        }

        var loader = new THREE.ObjectLoader();
        //loader.setResourcePath( scope.texturePath );
        var result = loader.parse( data );
        for(var i=result.children.length-1;i>=0;i--) {
            result.children[i].parent=null;
            _this.scene.add(result.children[i]);
            _this.objects.push(result.children[i]);
        }

        for (var item in objList) {
            var itemObj=objList[item];
            if(itemObj.length>0) {
                _this.LoadJSONModle(itemObj);
            }
        }

    });

}

p3D.prototype.LoadJSONModle = function (itemObj) {
    var _this = this;
    var mUrl = 'models/'+itemObj[0].userData.model;

    var loader = new THREE.JSONLoader();
    loader.load( mUrl, function ( geometry, materials ) {

        for(var i =itemObj.length-1;i>=0;i--) {
            var vmObj=itemObj[i];
            var matrix = new THREE.Matrix4();

            matrix.fromArray( vmObj.matrix );
            var grassGeometry = new THREE.BufferGeometry().fromGeometry( geometry );
            var plane = new THREE.Mesh( grassGeometry, materials );
            plane.userData=vmObj.userData;
            plane.name="cabinet_door";//vmObj.name;
            plane.applyMatrix(matrix);
            _this.scene.add( plane );
            _this.objects.push(plane);
        }

    } );
}

p3D.prototype.requestJSON = function (url, callback) {
    $.ajax({
        // async false-同步/true-异步
        // async: false,
        type: "get",
        dataType: "json",
        url: url,
        success: function (data) {
            callback(data);
        },
        error: function (error) {
            console.warn("请求JSON数据发生错误：", url, error);
        }
    });
}

 /*
 添加对象
 */
 p3D.prototype.InitAddObject = function (_obj) {
     var _this = this;
     if (_obj.show == null || typeof (_obj.show) == 'undefined' || _obj.show) {
         var _tempObj = null;
         switch (_obj.objType) {
             case 'cube':
                 _tempObj = _this.createCube(_this, _obj);
                 _this.addObject(_tempObj);
                 break;
             case 'floor':
                 _tempObj = _this.CreateFloor(_obj)
                 _this.addObject(_tempObj);
                 break;
             case 'wall':
                 _this.CreateWall(_this,_obj);
                 break;
             case 'plane':
                 _tempObj = _this.createPlaneGeometry(_this, _obj);
                 _this.addObject(_tempObj);
                 break;
             case 'glasses':
                 _this.createGlasses(_this, _obj);
                 break;
             case 'emptyCabinet':
                 _tempObj = _this.createEmptyCabinet(_this, _obj);
                 _this.addObject(_tempObj);
                 break;
             case 'cloneObj':
                 _tempObj = _this.commonFunc.cloneObj(_obj.copyfrom, _obj);
                 _this.addObject(_tempObj);
                 break;
			 case 'bladeServer':
                 _tempObj = _this.CreateBladeServer(_this, _obj)
                 //_this.addObject(_tempObj);
                 break;
			 case 'loadobj':
                 _this.loadObj(_obj);
                 break;
         }
     }
 }
 //创建地板
 p3D.prototype.CreateFloor = function (_obj) {
     var _this = this;
     var _cube = _this.createCube(_this, _obj);
     return _cube;
 }
 //刀片式服务器
 p3D.prototype.CreateBladeServer = function (_this, _obj) {
     if (_this == null) {
          _this = this;
     }

	 var vx=_obj.x,vy=_obj.y,vz=_obj.z;
	 //var group = new THREE.Object3D();
	 //_obj.x=0;
	 //_obj.y=0;
	 //_obj.z=0;
     var _cube = _this.createCube(_this, _obj);
	 //group.name=_obj.name;
	 //group.position.set(vx,vy,vz);
	 //group.add( _cube );
	 //_this.objects.push(_cube);
	 if (_this.commonFunc.hasObj(_obj.childrens) && _obj.childrens.length > 0) {
			 $.each(_obj.childrens, function (index, cardobj) {

				 var _newobj = _this.createCube(_this, cardobj);
				 //_newobj.parent=_cube;
				 //_this.addObject(_newobj);
				  _cube.add( _newobj );
				  _this.objects.push(_newobj);
			 });
	 }

	 _this.addObject(_cube);
     return _cube;
 }
 //刀片式服务器2
 p3D.prototype.CreateBladeServer2 = function (_this, _obj) {
     if (_this == null) {
          _this = this;
     }

     var _cube = _this.createCube(_this, _obj);
	 if (_this.commonFunc.hasObj(_obj.childrens) && _obj.childrens.length > 0) {
			 $.each(_obj.childrens, function (index, cardobj) {

				  var pcardobj = {
					 length: cardobj.length,
					 width: cardobj.width,
					 height: cardobj.height,
					 rotation: cardobj.rotation,
					 uuid: cardobj.uuid,
					 name: cardobj.name,
					 x: cardobj.x,
					 y: cardobj.y,
					 z: cardobj.z,
					 style: {
						 skinColor: cardobj.skinColor,
						 skin: cardobj.skin
					 }
				 }
				 var _newobj = _this.createCube(_this, pcardobj);
				 var vm = _cube.material.clone();
				 if( ''!= cardobj.op )
					_cube = _this.mergeModel(_this, cardobj.op, _cube, _newobj);
				 _cube.material=vm;
				 for(var m=0;m<66;m++)
					_cube.material.push(vm[m%6]);
			 });
	 }

	 _this.addObject(_cube);
     return _cube;
 }
 //创建墙体
 p3D.prototype.CreateWall = function (_this, _obj) {
    console.log('create wall');
     if (_this == null) {
          _this = this;
     }
     var _commonThick = _obj.thick || 40;//墙体厚度
     var _commonLength = _obj.length || 100;//墙体厚度
     var _commonHeight = _obj.height || 300;//强体高度
     var _commonSkin = _obj.style.skinColor || 0x98750f;
     //建立墙面
     $.each(_obj.wallData, function (index, wallobj) {
         var wallLength = _commonLength;
         var wallWidth = wallobj.thick||_commonThick;
         var positionX = ((wallobj.startDot.x||0) + (wallobj.endDot.x||0)) / 2;
         var positionY = ((wallobj.startDot.y || 0) + (wallobj.endDot.y || 0)) / 2;
         var positionZ = ((wallobj.startDot.z || 0) + (wallobj.endDot.z || 0)) / 2;
         //z相同 表示x方向为长度
         if (wallobj.startDot.z == wallobj.endDot.z) {
             wallLength = Math.abs(wallobj.startDot.x - wallobj.endDot.x);
             wallWidth = wallobj.thick || _commonThick;
         } else if (wallobj.startDot.x == wallobj.endDot.x) {
             wallLength = wallobj.thick || _commonThick;
             wallWidth = Math.abs(wallobj.startDot.z - wallobj.endDot.z);
         }
         var cubeobj = {
             length: wallLength,
             width: wallWidth,
             height: wallobj.height || _commonHeight,
             rotation: wallobj.rotation,
             x: positionX,
             y: positionY,
             z: positionZ,
             uuid: wallobj.uuid,
             name:wallobj.name,
             style: {
                 skinColor: _commonSkin,
                 skin:wallobj.skin
             }
         }
         var _cube = _this.createCube(_this, cubeobj);
         if (_this.commonFunc.hasObj(wallobj.childrens) && wallobj.childrens.length > 0) {
             $.each(wallobj.childrens, function (index, walchildobj) {
                 var _newobj = null;
                 _newobj = _this.CreateHole(_this, walchildobj);
                 _cube = _this.mergeModel(_this, walchildobj.op, _cube, _newobj);
             });
         }
         _this.addObject(_cube);
     });
 }
 //挖洞
 p3D.prototype.CreateHole = function (_this, _obj) {
     if (_this == null) {
         _this = this;
     }
     var _commonThick =  40;//墙体厚度
     var _commonLength =  100;//墙体厚度
     var _commonHeight =  300;//强体高度
     var _commonSkin = 0x98750f;
     //建立墙面
         var wallLength = _commonLength;
         var wallWidth = _obj.thick || _commonThick;
         var positionX = ((_obj.startDot.x || 0) + (_obj.endDot.x || 0)) / 2;
         var positionY = ((_obj.startDot.y || 0) + (_obj.endDot.y || 0)) / 2;
         var positionZ = ((_obj.startDot.z || 0) + (_obj.endDot.z || 0)) / 2;
         //z相同 表示x方向为长度
         if (_obj.startDot.z == _obj.endDot.z) {
             wallLength = Math.abs(_obj.startDot.x - _obj.endDot.x);
             wallWidth = _obj.thick || _commonThick;
         } else if (_obj.startDot.x == _obj.endDot.x) {
             wallLength = _obj.thick || _commonThick;
             wallWidth = Math.abs(_obj.startDot.z - _obj.endDot.z);
         }
         var cubeobj = {
             length: wallLength,
             width: wallWidth,
             height: _obj.height || _commonHeight,
             rotation: _obj.rotation,
             x: positionX,
             uuid: _obj.uuid,
             name: _obj.name,
             y: positionY,
             z: positionZ,
             style: {
                 skinColor: _commonSkin,
                 skin: _obj.skin
             }
         }
         var _cube = _this.createCube(_this, cubeobj);
         return _cube;
 }
 //模型合并 使用ThreeBSP插件mergeOP计算方式 -表示减去 +表示加上
 p3D.prototype.mergeModel2 = function (_this, mergeOP, _fobj, _sobj) {
     if (_this == null) {
         _this = this;
     }
     var fobjBSP = new ThreeBSP(_fobj);
     var sobjBSP = new ThreeBSP(_sobj);
    // var sobjBSP = new ThreeBSP(_sobj);
     var resultBSP = null;
     if (mergeOP == '-') {
         resultBSP = fobjBSP.subtract(sobjBSP);
     } else if (mergeOP == '+') {
         var subMesh = new THREE.Mesh(_sobj);
         _sobj.updateMatrix();
         _fobj.geometry.merge(_sobj.geometry, _sobj.matrix);
         return _fobj;
        // resultBSP = fobjBSP.union(sobjBSP);
     } else if (mergeOP == '&') {//交集
         resultBSP = fobjBSP.intersect(sobjBSP);
     } else {
         _this.addObject(_sobj);
         return _fobj;
     }
     var cubeMaterialArray = [];
     for (var i = 0; i < 1; i++) {
         cubeMaterialArray.push(new THREE.MeshLambertMaterial({
             //map: _this.createSkin(128, 128, { imgurl: '../datacenterdemo/res2/'+(i%11)+'.jpg' }),
             vertexColors: THREE.FaceColors
         }));
     }
     var cubeMaterials = cubeMaterialArray;
	 //allen
	 //cubeMaterials = _fobj.material.clone();
	 //var result = resultBSP.toMesh(cubeMaterials);
     var result = resultBSP.toMesh(cubeMaterials);
     result.material.shading = THREE.FlatShading;
     result.geometry.computeFaceNormals();
     result.geometry.computeVertexNormals();
     result.uuid= _fobj.uuid+mergeOP+_sobj.uuid;
     result.name=_fobj.name+mergeOP+_sobj.name;
     result.material.needsUpdate = true;
     result.geometry.buffersNeedUpdate = true;
     result.geometry.uvsNeedUpdate = true;

     result.castShadow = true;
     result.receiveShadow = true;
     return result;
 }
  //模型合并 使用ThreeBSP插件mergeOP计算方式 -表示减去 +表示加上
 p3D.prototype.mergeModel = function (_this, mergeOP, _fobj, _sobj) {
     if (_this == null) {
         _this = this;
     }
     var fobjBSP = new ThreeBSP(_fobj);
     var sobjBSP = new ThreeBSP(_sobj);
    // var sobjBSP = new ThreeBSP(_sobj);
     var resultBSP = null;
     if (mergeOP == '-') {
         resultBSP = fobjBSP.subtract(sobjBSP);
     } else if (mergeOP == '+') {
         var subMesh = new THREE.Mesh(_sobj);
         _sobj.updateMatrix();
         _fobj.geometry.merge(_sobj.geometry, _sobj.matrix);
         return _fobj;
        // resultBSP = fobjBSP.union(sobjBSP);
     } else if (mergeOP == '&') {//交集
         resultBSP = fobjBSP.intersect(sobjBSP);
     } else {
         _this.addObject(_sobj);
         return _fobj;
     }
     var cubeMaterialArray = [];
     for (var i = 0; i < 1; i++) {
         cubeMaterialArray.push(new THREE.MeshLambertMaterial({
             //map: _this.createSkin(128, 128, { imgurl: '../datacenterdemo/res2/'+(i%11)+'.jpg' }),
             vertexColors: THREE.FaceColors
         }));
     }
     var cubeMaterials = cubeMaterialArray;
	 //allen
	 //cubeMaterials = _fobj.material.clone();
	 //var result = resultBSP.toMesh(cubeMaterials);
     var result = resultBSP.toMesh(cubeMaterials);
     result.material.shading = THREE.FlatShading;
     result.geometry.computeFaceNormals();
     result.geometry.computeVertexNormals();
     result.uuid= _fobj.uuid+mergeOP+_sobj.uuid;
     result.name=_fobj.name+mergeOP+_sobj.name;
     result.material.needsUpdate = true;
     result.geometry.buffersNeedUpdate = true;
     result.geometry.uvsNeedUpdate = true;
     var _foreFaceSkin = null;
     for (var i = 0; i < result.geometry.faces.length; i++) {
         var _faceset = false;
         for (var j = 0; j < _fobj.geometry.faces.length; j++) {
             if (result.geometry.faces[i].vertexNormals[0].x === _fobj.geometry.faces[j].vertexNormals[0].x
                 && result.geometry.faces[i].vertexNormals[0].y === _fobj.geometry.faces[j].vertexNormals[0].y
                 && result.geometry.faces[i].vertexNormals[0].z === _fobj.geometry.faces[j].vertexNormals[0].z
                  && result.geometry.faces[i].vertexNormals[1].x === _fobj.geometry.faces[j].vertexNormals[1].x
                 && result.geometry.faces[i].vertexNormals[1].y === _fobj.geometry.faces[j].vertexNormals[1].y
                 && result.geometry.faces[i].vertexNormals[1].z === _fobj.geometry.faces[j].vertexNormals[1].z
                 && result.geometry.faces[i].vertexNormals[2].x === _fobj.geometry.faces[j].vertexNormals[2].x
                 && result.geometry.faces[i].vertexNormals[2].y === _fobj.geometry.faces[j].vertexNormals[2].y
                 && result.geometry.faces[i].vertexNormals[2].z === _fobj.geometry.faces[j].vertexNormals[2].z) {
                 result.geometry.faces[i].color.setHex(_fobj.geometry.faces[j].color.r * 0xff0000 + _fobj.geometry.faces[j].color.g * 0x00ff00 + _fobj.geometry.faces[j].color.b * 0x0000ff);
                 _foreFaceSkin = _fobj.geometry.faces[j].color.r * 0xff0000 + _fobj.geometry.faces[j].color.g * 0x00ff00 + _fobj.geometry.faces[j].color.b * 0x0000ff;
                 _faceset =true;
             }
         }
         if (_faceset == false){
             for(var j = 0; j < _sobj.geometry.faces.length; j++) {
                 if (result.geometry.faces[i].vertexNormals[0].x === _sobj.geometry.faces[j].vertexNormals[0].x
                     && result.geometry.faces[i].vertexNormals[0].y === _sobj.geometry.faces[j].vertexNormals[0].y
                     && result.geometry.faces[i].vertexNormals[0].z === _sobj.geometry.faces[j].vertexNormals[0].z
                      && result.geometry.faces[i].vertexNormals[1].x === _sobj.geometry.faces[j].vertexNormals[1].x
                     && result.geometry.faces[i].vertexNormals[1].y === _sobj.geometry.faces[j].vertexNormals[1].y
                     && result.geometry.faces[i].vertexNormals[1].z === _sobj.geometry.faces[j].vertexNormals[1].z
                     && result.geometry.faces[i].vertexNormals[2].x === _sobj.geometry.faces[j].vertexNormals[2].x
                     && result.geometry.faces[i].vertexNormals[2].y === _sobj.geometry.faces[j].vertexNormals[2].y
                     && result.geometry.faces[i].vertexNormals[2].z === _sobj.geometry.faces[j].vertexNormals[2].z
                     && result.geometry.faces[i].vertexNormals[2].z === _sobj.geometry.faces[j].vertexNormals[2].z) {
                     result.geometry.faces[i].color.setHex(_sobj.geometry.faces[j].color.r * 0xff0000 + _sobj.geometry.faces[j].color.g * 0x00ff00 + _sobj.geometry.faces[j].color.b * 0x0000ff);
                     _foreFaceSkin = _sobj.geometry.faces[j].color.r * 0xff0000 + _sobj.geometry.faces[j].color.g * 0x00ff00 + _sobj.geometry.faces[j].color.b * 0x0000ff;
                     _faceset = true;
                 }
             }
         }
         if (_faceset == false) {
             result.geometry.faces[i].color.setHex(_foreFaceSkin);
         }
     // result.geometry.faces[i].materialIndex = i
     }
     result.castShadow = true;
     result.receiveShadow = true;
     return result;
 }
 //创建盒子体
 p3D.prototype.createCube = function (_this, _obj) {
     if (_this == null) {
         _this = this;
     }
     var _length = _obj.length || 1000;//默认1000
     var _width = _obj.width || _length;
     var _height = _obj.height || 10;
     var _x = _obj.x || 0, _y = _obj.y || 0, _z = _obj.z || 0;
     var skinColor = _obj.style.skinColor || 0x98750f;
     var cubeGeometry = new THREE.CubeGeometry(_length, _height, _width, 0, 0, 1);

     //六面颜色
     for (var i = 0; i < cubeGeometry.faces.length; i += 2) {
         var hex = skinColor || Math.random() * 0x531844;
         cubeGeometry.faces[i].color.setHex(hex);
         cubeGeometry.faces[i + 1].color.setHex(hex);
     }
     //六面纹理
     var skin_up_obj = {
         vertexColors: THREE.FaceColors
     }
     var skin_down_obj = skin_up_obj,
         skin_fore_obj = skin_up_obj,
         skin_behind_obj = skin_up_obj,
         skin_left_obj = skin_up_obj,
         skin_right_obj = skin_up_obj;
     var skin_opacity = 1;
     if (_obj.style != null && typeof (_obj.style) != 'undefined'
         && _obj.style.skin != null && typeof (_obj.style.skin) != 'undefined') {
         //透明度
         if (_obj.style.skin.opacity != null && typeof (_obj.style.skin.opacity) != 'undefined') {
             skin_opacity = _obj.style.skin.opacity;
             console.log(skin_opacity)
         }
         //上
         skin_up_obj = _this.createSkinOptionOnj(_this, _length, _width, _obj.style.skin.skin_up, cubeGeometry, 4);
         //下
         skin_down_obj = _this.createSkinOptionOnj(_this, _length, _width, _obj.style.skin.skin_down, cubeGeometry, 6);
         //前
         skin_fore_obj = _this.createSkinOptionOnj(_this, _length, _width, _obj.style.skin.skin_fore, cubeGeometry, 0);
         //后
         skin_behind_obj = _this.createSkinOptionOnj(_this, _length, _width, _obj.style.skin.skin_behind, cubeGeometry, 2);
         //左
         skin_left_obj = _this.createSkinOptionOnj(_this, _length, _width, _obj.style.skin.skin_left, cubeGeometry, 8);
         //右
         skin_right_obj = _this.createSkinOptionOnj(_this, _length, _width, _obj.style.skin.skin_right, cubeGeometry, 10);
     }
     var cubeMaterialArray = [];
     cubeMaterialArray.push(new THREE.MeshLambertMaterial(skin_fore_obj));
     cubeMaterialArray.push(new THREE.MeshLambertMaterial(skin_behind_obj));
     cubeMaterialArray.push(new THREE.MeshLambertMaterial(skin_up_obj));
     cubeMaterialArray.push(new THREE.MeshLambertMaterial(skin_down_obj));
     cubeMaterialArray.push(new THREE.MeshLambertMaterial(skin_right_obj));
     cubeMaterialArray.push(new THREE.MeshLambertMaterial(skin_left_obj));
     var cubeMaterials = cubeMaterialArray;
     cube = new THREE.Mesh(cubeGeometry, cubeMaterials);
     cube.castShadow = true;
     cube.receiveShadow = true;
     cube.uuid = _obj.uuid;
     cube.name = _obj.name;
     cube.position.set(_x, _y, _z);
     if (_obj.rotation != null && typeof (_obj.rotation) != 'undefined' && _obj.rotation.length > 0) {
         $.each(_obj.rotation, function (index, rotation_obj) {
             switch (rotation_obj.direction) {
                 case 'x':
                     cube.rotateX(rotation_obj.degree);
                     break;
                 case 'y':
                     cube.rotateY(rotation_obj.degree);
                     break;
                 case 'z':
                     cube.rotateZ(rotation_obj.degree);
                     break;
                 case 'arb':
                     cube.rotateOnAxis(new THREE.Vector3(rotation_obj.degree[0], rotation_obj.degree[1], rotation_obj.degree[2]), rotation_obj.degree[3]);
                     break;
             }
         });
     }

     return cube;
 }
 //创建二维平面-长方形
 p3D.prototype.createPlaneGeometry = function (_this,_obj) {
           //options={
           //    width:0,
           //    height:0,
           //    pic:"",
           //    transparent:true,
           //    opacity:1
     //    blending:false,
     //position: { x:,y:,z:},
     //rotation: { x:,y:,z:},
     //}

    var  options = _obj;
     if (typeof options.pic == "string") {//传入的材质是图片路径，使用 textureloader加载图片作为材质
         var loader = new THREE.TextureLoader();
         loader.setCrossOrigin(this.crossOrigin);
         var texture = loader.load(options.pic, function () { }, undefined, function () { });
     } else {
         var texture = new THREE.CanvasTexture(options.pic)
     }
     var MaterParam = {//材质的参数
         map: texture,
         side: THREE.FrontSide,
         //blending: THREE.AdditiveBlending,
         transparent: options.transparent,
         //needsUpdate:true,
         //premultipliedAlpha: true,
         opacity: options.opacity
     }
     if (options.blending) {
         MaterParam.blending = THREE.AdditiveBlending//使用饱和度叠加渲染
     }
     var plane = new THREE.Mesh(
         new THREE.PlaneGeometry(options.width, options.height, 1, 1),
         new THREE.MeshBasicMaterial(MaterParam)
     );
     plane.position.x = options.position.x;
     plane.position.y = options.position.y;
     plane.position.z = options.position.z;
     plane.rotation.x = options.rotation.x;
     plane.rotation.y = options.rotation.y;
     plane.rotation.z = options.rotation.z;
     return plane;
 }
 //创建空柜子
 p3D.prototype.createEmptyCabinet = function (_this, _obj) {
     /* 参数demo
     {
     show:true,
     name: 'test',
     uuid: 'test',
    rotation: [{ direction: 'y', degree: 0.25*Math.PI}],//旋转     uuid:'',
     objType: 'emptyCabinet',
     transparent:true,
     size:{length:50,width:60,height:200, thick:2},
     position: { x: -220, y: 105, z: -150 },
     doors: {
         doorType:'lr',// ud门 lr左右门
         doorSize:[1],
         skins:[ {
             skinColor: 0x333333,
             skin_fore: {
                 imgurl: "../datacenterdemo/mng/rack_door_back.jpg",
             },
             skin_behind: {
                 imgurl: "../datacenterdemo/mng/rack_front_door.jpg",
             }
         }]
     },
     skin:{
             skinColor: 0xdddddd,

                 skin:{
                             skinColor: 0xdddddd,
                             skin_up: { imgurl: "../datacenterdemo/mng/rack_door_back.jpg" },
                             skin_down: { imgurl: "../datacenterdemo/mng/rack_door_back.jpg" },
                             skin_fore: { imgurl: "../datacenterdemo/mng/rack_door_back.jpg" },
                             skin_behind: { imgurl: "../datacenterdemo/mng/rack_door_back.jpg" },
                             skin_left: { imgurl: "../datacenterdemo/mng/rack_door_back.jpg" },
                             skin_right: { imgurl: "../datacenterdemo/mng/rack_door_back.jpg" },
                 }

         }
 }
     */
     var _this = p3DObj;
     //创建五个面
     //上
     var upobj= {
         show: true,
         uuid: "",
         name: '',
         objType: 'cube',
         length: _obj.size.length+1,
         width: _obj.size.width ,
         height: _obj.size.thick + 1,
         x: _obj.position.x+1,
         y: _obj.position.y+(_obj.size.height/2-_obj.size.thick/2),
         z:_obj.position.z,
         style: {
             skinColor: _obj.skin.skinColor,
             skin: _obj.skin.skin_up.skin
         }
     }
     var upcube = _this.createCube(_this, upobj);
     //左
     var leftobj = {
         show: true,
         uuid: "",
         name: '',
         objType: 'cube',
         length: _obj.size.length,
         width: _obj.size.thick,
         height: _obj.size.height,
         x: 0,
         y: -(_obj.size.height / 2 - _obj.size.thick / 2),
         z: 0 - (_obj.size.width / 2 - _obj.size.thick / 2) - 1,
         style: {
             skinColor: _obj.skin.skinColor,
             skin: _obj.skin.skin_left.skin
         }
     }
     var leftcube = _this.createCube(_this, leftobj);
     var Cabinet = _this.mergeModel(_this, '+', upcube, leftcube);
     //右
     var Rightobj = {
         show: true,
         uuid: "",
         name: '',
         objType: 'cube',
         length: _obj.size.length,
         width: _obj.size.thick,
         height: _obj.size.height,
         x: 0,
         y: -(_obj.size.height / 2 - _obj.size.thick / 2),
         z: (_obj.size.width / 2 - _obj.size.thick / 2)+1,
         style: {
             skinColor: _obj.skin.skinColor,
             skin: _obj.skin.skin_right.skin
         }
     }
     var Rightcube = _this.createCube(_this, Rightobj);
     Cabinet = _this.mergeModel(_this, '+', Cabinet, Rightcube);
     //后
     var Behidobj = {
         show: true,
         uuid: "",
         name: '',
         objType: 'cube',
         length: _obj.size.thick,
         width: _obj.size.width,
         height: _obj.size.height,
         x: (_obj.size.length / 2 - _obj.size.thick / 2)+1,
         y: -(_obj.size.height / 2 - _obj.size.thick / 2),
         z:0,
         style: {
             skinColor: _obj.skin.skinColor,
            skin: _obj.skin.skin_behind.skin
         }
     }
     var Behindcube = _this.createCube(_this, Behidobj);
     Cabinet = _this.mergeModel(_this, '+', Cabinet, Behindcube);
     //下
     var Downobj = {
         show: true,
         uuid: "",
         name: '',
         objType: 'cube',
         length: _obj.size.length+1,
         width: _obj.size.width,
         height: _obj.size.thick,
         x:-1,
         y: -(_obj.size.height- _obj.size.thick)-1,
         z: 0,
         style: {
             skinColor: _obj.skin.skinColor,
             skin: _obj.skin.skin_down.skin
         }
     }
     var Downcube = _this.createCube(_this, Downobj);
     Cabinet = _this.mergeModel(_this, '+', Cabinet, Downcube);

     var tempobj = new THREE.Object3D();
     tempobj.add(Cabinet);
     tempobj.name = _obj.name;
     tempobj.uuid = _obj.uuid;
     Cabinet.name = _obj.shellname,
     _this.objects.push(Cabinet);
     tempobj.position = Cabinet.position;
     //门
     if (_obj.doors != null && typeof (_obj.doors) != 'undefined') {
         var doors = _obj.doors;
         if (doors.skins.length == 1) {//单门
             var singledoorobj = {
                 show: true,
                 uuid:"",
                 name: _obj.doors.doorname[0],
                 objType: 'cube',
                 length: _obj.size.thick,
                 width: _obj.size.width,
                 height: _obj.size.height,
                 x: _obj.position.x - _obj.size.length / 2 - _obj.size.thick / 2,
                 y: _obj.position.y,
                 z: _obj.position.z,
                 style: {
                     skinColor: _obj.doors.skins[0].skinColor,
                     skin: _obj.doors.skins[0]
                 }
             }
             var singledoorcube = _this.createCube(_this, singledoorobj);
             _this.objects.push(singledoorcube);
             tempobj.add(singledoorcube);
         } else if (doors.skins.length > 1) {//多门

         }

     }

     if (_obj.rotation != null && typeof (_obj.rotation) != 'undefined' && _obj.rotation.length > 0) {
         $.each(_obj.rotation, function (index, rotation_obj) {
             switch (rotation_obj.direction) {
                 case 'x':
                     tempobj.rotateX(rotation_obj.degree);
                     break;
                 case 'y':
                     tempobj.rotateY(rotation_obj.degree);
                     break;
                 case 'z':
                     tempobj.rotateZ(rotation_obj.degree);
                     break;
                 case 'arb':
                     tempobj.rotateOnAxis(new THREE.Vector3(rotation_obj.degree[0], rotation_obj.degree[1], rotation_obj.degree[2]), rotation_obj.degree[3]);
                     break;
             }
         });
     }
     return tempobj;
 }
 //创建玻璃
 p3D.prototype.createGlasses = function (_this, _obj) {
     var _this = p3DObj;
     var tmpobj = _this.createPlaneGeometry(_this, _obj);
     _this.addObject(tmpobj);
     _obj.rotation.y = Math.PI + _obj.rotation.y;
     var tmpobj2 = _this.createPlaneGeometry(_this, _obj);
     _this.addObject(tmpobj2);
 }
 //创建皮肤
 p3D.prototype.createSkin = function (flength,fwidth,_obj) {
     var imgwidth = 128,imgheight=128;
     if (_obj.width != null&& typeof (_obj.width) != 'undefined') {
         imgwidth = _obj.width;
     }
     if (_obj.height != null && typeof (_obj.height) != 'undefined') {
         imgheight = _obj.height;
     }
     var texture = new THREE.TextureLoader().load(_obj.imgurl);
     var _repeat = false;
     if (_obj.repeatx != null && typeof (_obj.repeatx) != 'undefined' && _obj.repeatx==true) {
         texture.wrapS = THREE.RepeatWrapping;
         _repeat = true;
     }
     if (_obj.repeaty != null && typeof (_obj.repeaty) != 'undefined' && _obj.repeaty == true) {
         texture.wrapT = THREE.RepeatWrapping;
         _repeat = true;
     }
     if (_repeat) {
         texture.repeat.set(flength / imgheight, fwidth / imgheight);
     }
     return texture;
 }
 //创建皮肤参数对象
 p3D.prototype.createSkinOptionOnj = function (_this, flength, fwidth, _obj, _cube, _cubefacenub) {
     if (_this.commonFunc.hasObj(_obj)) {
         if (_this.commonFunc.hasObj(_obj.imgurl)) {
             return {
                 map: _this.createSkin(flength, fwidth, _obj),transparent:true,
				 //emissive: 0x00ff00,
             }
         } else {
             if (_this.commonFunc.hasObj(_obj.skinColor)) {
                 _cube.faces[_cubefacenub].color.setHex(_obj.skinColor);
                 _cube.faces[_cubefacenub + 1].color.setHex(_obj.skinColor);
             }
             return {
                 vertexColors: THREE.FaceColors
             }
         }
     } else {
         return {
             vertexColors: THREE.FaceColors
         }
     }
 }
 //通用方法
 p3D.prototype.commonFunc={
     //判断对象
     hasObj: function (_obj) {
         if (_obj != null && typeof (_obj) != 'undefined') {
             return true;
         }else{
             return false;
         }
     },
     //查找对象
     findObject: function (_objname) {
         var _this = p3DObj;
         console.log('findObject');
         var findedobj = null;
         $.each(_this.objects, function (index,_obj) {
             if (_obj.name != null && _obj.name != '') {
                 if (_obj.name == _objname) {
                     findedobj = _obj;
                     //return true;
					 return findedobj;
                 }
             }
         });
         return findedobj;
     },
     //复制对象
     cloneObj: function (_objname, newparam) {
         /*newparam
         {
         show: true,
         uuid:
         copyfrom: 'cabinet1_1',
         name:
         childrenname:[]
         objType: 'cloneObj',
         position:{x:y:z:}//相对复制品的
         scale:{x:1,y:1,z:1}
          rotation: [{ direction: 'y', degree: 0.25*Math.PI}],//旋转     uuid:'',
         }
         */
         var _this = p3DObj;
         var fobj = _this.commonFunc.findObject(_objname);
         var newobj = fobj.clone();
         if (newobj.children != null && newobj.children.length > 1) {
             $.each(newobj.children, function (index, obj) {
                 obj.name = newparam.childrenname[index];
                 _this.objects.push(obj);
             });
         }
         //位置
         if (_this.commonFunc.hasObj(newparam.position)) {
             newobj.position.x = newparam.position.x;
             newobj.position.y = newparam.position.y;
             newobj.position.z = newparam.position.z;
         }
         //大小
         if (_this.commonFunc.hasObj(newparam.scale)) {
             newobj.scale.x = newparam.scale.x;
             newobj.scale.y = newparam.scale.y;
             newobj.scale.z = newparam.scale.z;
         }
         //角度
         if (_this.commonFunc.hasObj(newparam.rotation)) {
             $.each(newparam.rotation, function (index, rotation_obj) {
                     switch (rotation_obj.direction) {
                         case 'x':
                             newobj.rotateX(rotation_obj.degree);
                             break;
                         case 'y':
                             newobj.rotateY(rotation_obj.degree);
                             break;
                         case 'z':
                             newobj.rotateZ(rotation_obj.degree);
                             break;
                         case 'arb':
                             newobj.rotateOnAxis(new THREE.Vector3(rotation_obj.degree[0], rotation_obj.degree[1], rotation_obj.degree[2]), rotation_obj.degree[3]);
                             break;
                     }
                 });
         }
         newobj.name = newparam.name;
         newobj.uuid = newparam.uuid;
         return newobj;
     },
     //设置表皮颜色
     setSkinColor: function (_objname, _color) {
         var _this = p3DObj;
         var _obj = _this.commonFunc.findObject(_objname);
		 //alert(_obj.material);
		 //alert(_obj.material.length);
		 //_obj.material.emissive != null &&typeof (_obj.material.emissive) != 'undefined' &&
         if (_this.commonFunc.hasObj(_obj.material.emissive)) {
			 alert(73);
             _obj.material.emissive.setHex(_color);
			 alert(2);
         } else if (_this.commonFunc.hasObj(_obj.material.materials)) {
			 //alert(53);
             if (_obj.material.materials.length > 0) {
                 $.each(_obj.material.materials, function (index,obj) {
                     obj.emissive.setHex(_color);
					 //alert(5);
                 });
             }
         } else if (_obj.material.length>0) {
			 //alert(53);
			 $.each(_obj.material, function (index,obj) {
				 obj.emissive.setHex(_color);
			 });

         }
		 else if (_this.commonFunc.hasObj(_obj.children)) {
			 //alert(13);
			 var vchildren=_obj.children[0];
			 $.each(vchildren.material, function (index,obj) {
				 obj.emissive.setHex(_color);
			 });
         }
     },
     //添加图片标识
     addIdentification: function (_objname, _obj) {
         /*
		   {
			 name:'test',
			 size:{x:20,y:20},
			 position:{x:0,y:100,z:0},
			 imgurl: '../datacenterdemo/mng/connection.png'
		   }
         */
         var _this = p3DObj;
         var _fobj = _this.commonFunc.findObject(_objname);
         var loader = new THREE.TextureLoader();
         var texture = loader.load(_obj.imgurl, function () { }, undefined, function () { });
         var spriteMaterial = new THREE.SpriteMaterial({ map: texture, useScreenCoordinates: false });
         var sprite = new THREE.Sprite(spriteMaterial);
         sprite.name = _obj.name;
         sprite.position.x = _fobj.position.x + _obj.position.x;
         sprite.position.y = _fobj.position.y + _obj.position.y;
         sprite.position.z = _fobj.position.z + _obj.position.z;
         if (_this.commonFunc.hasObj(_obj.size)) {
             sprite.scale.set(_obj.size.x, _obj.size.y);
         } else {
             sprite.scale.set(1,1);
         }
         _this.addObject(sprite);
     },
     //添加文字
     makeTextSprite: function (_objname, parameters)
     {
         /*
		   {
			 name:'nettext',
			 position:{x:0,y:100,z:0},
			 size:{x:20,y:20},
			 color:{r:255, g:255, b:255, a:1.0},
			 imgurl: '../datacenterdemo/mng/connection.png',
			 rows: [
			   {
				 name:'item1',
				 fontface:'Arial',
				 fontsize:18,
				 borderThickness:8,
				 textColor:{r:255, g:255, b:255, a:1.0},
				 text:'',
				 size:{x:20,y:20},
				 position:{x:0,y:100,z:0},
			   },
			 ]
		   }
         */
		 var vWidth = 512;
		 var vheight = vWidth/2;
         var _this = p3DObj;
         var _fobj = _this.commonFunc.findObject(_objname);

        if ( parameters === undefined || parameters === null ) parameters = {};
         var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Arial";
         var fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 18;
         var borderThickness = parameters.hasOwnProperty("borderThickness") ? parameters["borderThickness"] : 4;
         var textColor = parameters.hasOwnProperty("textColor") ?parameters["textColor"] : { r:255, g:255, b:255, a:1.0 };
         var message = parameters.hasOwnProperty("message") ? parameters["message"] : "Please 3D机房";
         var x = parameters.hasOwnProperty("position") ? parameters["position"].x : 10;
         var y = parameters.hasOwnProperty("position") ? parameters["position"].y : 80;
         var z = parameters.hasOwnProperty("position") ? parameters["position"].z : 0;

         var canvas = document.createElement('canvas');
		 canvas.width = vWidth;
         canvas.height = vheight;
         var context = canvas.getContext('2d');
		 vcanvas=canvas;
		 vcontext=context;

		 context.fillStyle = "rgb(255,127,39)";
		 context.fillRect(0,0,vWidth,fontsize*4+borderThickness);
		 //alert(vheight);

		 context.fillStyle = 'black';
		 context.textAlign = 'center';
         context.textBaseline = 'middle';
         context.font = "bold " + fontsize + "px " + fontface;
         context.lineWidth = borderThickness;
         context.fillStyle = "rgba("+textColor.r+", "+textColor.g+", "+textColor.b+", 1.0)";
         context.fillText(message, vWidth/2, fontsize + borderThickness);
		 //context.strokeStyle='black';
         //context.lineWidth=borderThickness;
         //context.strokeText(message, vWidth/2, fontsize + borderThickness);
		 context.fillText(message, vWidth/2, fontsize + borderThickness + fontsize);

		 var metrics = context.measureText( message );
		 var textWidth = metrics.width;

         var texture = new THREE.Texture(canvas)
         texture.needsUpdate = true;
         var spriteMaterial = new THREE.SpriteMaterial( { map: texture, useScreenCoordinates: false } );
         var sprite = new THREE.Sprite(spriteMaterial);
         sprite.position.x =_fobj.position.x + x;
         sprite.position.y = _fobj.position.y + y;
         sprite.position.z = _fobj.position.z + z;
         sprite.name = parameters.name;
         sprite.scale.set(7.5 * fontsize, 5.0 * fontsize, 1.0);
         _this.addObject(sprite);

		 //context.clearRect(0, 0, canvas.width, canvas.height);
		 //context.fillText("dddddddddddd", vWidth/2, fontsize + borderThickness);
	 },
     //添加dt文字
     makeDynamicTextSprite: function (_objname, parameters)
     {
		 /*
		 var _this = p3DObj;
		 var canvas = _this.vcanvas;
         var context2 = _this.vcontext;

		 context2.clearRect(0, 0, canvas.width, canvas.height);
		 context2.fillText(_objname+"%", 256, 22);
		 //alert(canvas.width);

		context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
		context.strokeStyle = "#fff"; //设置描边样式
		context.font = "80px Arial"; //设置字体大小和字体

		//绘制字体，并且指定位置
		context.fillText(_objname+"%", 256, 22);
		//context.strokeText(_objname+"%", 256, 22);
		context.stroke(); //执行绘制
		context.restore();
		*/
         var _this = p3DObj;
		 var vobjx = 0;
		 var vobjy = 0;
		 var vobjz = 0;
         var _fobj = _this.commonFunc.findObject(_objname);
		 if ( _fobj != undefined && _fobj != null ) {
			 vobjx = _fobj.position.x;
			 vobjy = _fobj.position.y;
			 vobjz = _fobj.position.z;
		 };

         if ( parameters === undefined || parameters === null ) parameters = {};
         var vname = parameters.hasOwnProperty("name") ? parameters["name"] : "mark";
         var vbkColor = parameters.hasOwnProperty("color") ?parameters["color"] : { r:255, g:255, b:255, a:1.0 };
         var imgurl = parameters.hasOwnProperty("imgurl") ? parameters["imgurl"] : "mng/floor2.jpg";
         var x = parameters.hasOwnProperty("position") ? parameters["position"].x : 10;
         var y = parameters.hasOwnProperty("position") ? parameters["position"].y : 80;
         var z = parameters.hasOwnProperty("position") ? parameters["position"].z : 0;
		 var vWidth = parameters.hasOwnProperty("size") ? parameters["size"].x : 128;
		 var vheight = parameters.hasOwnProperty("size") ? parameters["size"].y : 64;
		 var vscale = parameters.hasOwnProperty("size") ? parameters["size"].z : 18;

         var canvas = document.createElement('canvas');
		 canvas.width = vWidth;
         canvas.height = vheight;
         var context = canvas.getContext('2d');

		 var clockImage = new Image();
		 if ( imgurl != undefined && imgurl != null && imgurl != '' ) {
			 clockImage.src = imgurl;	//'mng/floor2.jpg';
			 clockImage.onload = function () {
				context.drawImage(clockImage, 0, 0, vWidth, vheight);
			 };
		 } else {
			 context.fillStyle = "rgba("+vbkColor.r+", "+vbkColor.g+", "+vbkColor.b+", "+vbkColor.a +" )";
			 context.fillRect(0,0,vWidth,vheight);
		 }

		if (parameters.rows != null && parameters.rows.length > 0) {
			 $.each(parameters.rows, function (index,_obj) {
				 var fontsize = _obj.fontsize;
				 var fontface = _obj.fontface;
				 var borderThickness = _obj.borderThickness;
				 var message = _obj.text;
				 var textColor= _obj.textColor;
				 var vix = _obj.position.x;
				 var viy = _obj.position.y;
				 var viz = _obj.position.z;
				 context.textAlign = 'left';
				 context.textBaseline = 'middle';
				 context.font = "bold " + fontsize + "px " + fontface;
				 context.lineWidth = borderThickness;
				 context.fillStyle = "rgba("+textColor.r+", "+textColor.g+", "+textColor.b+", 1.0)";
				 context.fillText(message, vix, viy);
			 });
		}

		 var texture = new THREE.Texture(canvas);
         texture.needsUpdate = true;
         var spriteMaterial = new THREE.SpriteMaterial( { map: texture} );
         var sprite = new THREE.Sprite(spriteMaterial);
         sprite.position.x = vobjx + x;
         sprite.position.y = vobjy + y;
         sprite.position.z = vobjz + z;
         sprite.name = parameters.name;
         sprite.scale.set(1.0 * vscale, vheight/vWidth * vscale, 1.0);
         _this.addObject(sprite);
		 ////
		 _this.vcanvas=canvas;
		 _this.vspriteMaterial=spriteMaterial;

		 //clearInterval(_this.mtTimer);
		 _this.mtTimer=setInterval(function()
		 {
			_this.commonFunc.makeItemValue("",'item2',parameters);
		 }, 1000);

		 return null;
	 },
     //
     makeItemValue: function (objname,objitem,objparameters)
     {
		 var _this = p3DObj;
		 var canvas=_this.vcanvas;

		  if (canvas != null && typeof (canvas) != 'undefined') {
			var context = canvas.getContext('2d');

			 var vWidth = canvas.width;
			 var vheight = canvas.height;
			 var vbkColor = objparameters.color;
			 var imgurl = objparameters.imgurl;
			 var clockImage = new Image();
			 if ( imgurl != undefined && imgurl != null && imgurl != '' ) {
				 clockImage.src = imgurl;	//'mng/floor2.jpg';
				 context.drawImage(clockImage, 0, 0, vWidth, vheight);
			 } else {
				 context.clearRect(0,0,vWidth,vheight);
				 context.fillStyle = "rgba("+vbkColor.r+", "+vbkColor.g+", "+vbkColor.b+", "+vbkColor.a +" )";
				 context.fillRect(0,0,vWidth,vheight);
			 }

			var theDate = new Date();
			var msgtext=theDate.getMilliseconds().toString()+theDate.getSeconds().toString();
			if (objparameters.rows != null && objparameters.rows.length > 0) {
				 $.each(objparameters.rows, function (index,_obj) {
					 var fontsize = _obj.fontsize;
					 var fontface = _obj.fontface;
					 var borderThickness = _obj.borderThickness;
					 var message = _obj.text;
					 if(_obj.name == objitem)
						 message = msgtext;
					 var textColor= _obj.textColor;
					 var vix = _obj.position.x;
					 var viy = _obj.position.y;
					 var viz = _obj.position.z;
					 context.textAlign = 'left';
					 context.textBaseline = 'middle';
					 context.font = "bold " + fontsize + "px " + fontface;
					 context.lineWidth = borderThickness;
					 context.fillStyle = "rgba("+textColor.r+", "+textColor.g+", "+textColor.b+", 1.0)";
					 context.fillText(message, vix, viy);
				 });
			}
			 /*
			var clockImage = new Image();
			clockImage.src = 'mng/textmark.jpg';
			context.drawImage(clockImage, 0, 0, canvas.width, canvas.height);
			var theDate = new Date();
			//theDate.getHours().toString()+theDate.getMinutes().toString()+
			var msgtext=theDate.getSeconds().toString()+theDate.getMilliseconds().toString();
			context.fillText(msgtext, 10, 80);
			*/

			 _this.vspriteMaterial.map.needsUpdate = true;
		 }
     }
 }

 p3D.prototype.loadObj = function (_obj) {
	  /*
	   {
		 name:'objname001',
		 type:'camera',
		 visible:true,
		 position:{x:-130,y:240,z:360},
		 size:{x:1,y:1,z:1},
		 rotation: { x:0,y:0,z:0},
		 modelurl: './mng/model.json',
	   }
	 */
	 var _this = p3DObj;

	 /*
     var jsloader = new THREE.JSONLoader();
	 //alert(jsloader);

	 function modelLoadedCallback(geometry, materials) {
		 alert(3);
             var model = new THREE.SkinnedMesh(geometry, materials);

             model.name = 'test';
             model.scale.x = 10;
             model.scale.y = 7;
             model.scale.z = 10;
             model.position.x = -130;
             model.position.y = 165;
             model.position.z = -180;
             _this.addObject(model);

         };
	 jsloader.load("pressure.json",modelLoadedCallback);


     jsloader.load("model.json",
         function (geometry, materials) {
			 alert(1);
             var model = new THREE.SkinnedMesh(geometry, materials);

             model.name = 'test';
             model.scale.x = 10;
             model.scale.y = 7;
             model.scale.z = 10;
             model.position.x = -130;
             model.position.y = 165;
             model.position.z = -180;
             _this.addObject(model);

         });

		 */

		var objectLoader = new THREE.ObjectLoader();
		//alert(objectLoader);
		objectLoader.load(_obj.modelurl, function (obj) {

			obj.name= _obj.name;
			//alert(33);
			obj.scale.x = _obj.size.x;
            obj.scale.y = _obj.size.y;
            obj.scale.z = _obj.size.z;
			obj.position.x=_obj.position.x;
			obj.position.y=_obj.position.y;
			obj.position.z =_obj.position.z;

			_this.addObject(obj);

			//scene.add(obj);

		});

 }

 //添加按钮
 p3D.prototype.addBtns = function (_btnobjs) {
    var _this = p3DObj;
	var container=$("#" + _this.fId);

	var info = document.createElement( 'div' );
	info.style.position = 'absolute';
	info.style.top = '10px';
	info.style.right = '20px';
	info.style.width = '60%';
	info.style.textAlign = 'right';
	info.style.zIndex=100;
	info.id='menutoolbar';
	//info.innerHTML = '<button type="button" onclick="butClick()">Remove OBJ</button>';

     if (_btnobjs != null && _btnobjs.length > 0) {
         container.append(info);
         $.each(_btnobjs, function (index,_obj) {
             $("#menutoolbar").append(' <img src="' + _obj.btnimg + '" title="' + _obj.btnTitle + '" id="' + _obj.btnid + '" />');
             $("#" + _obj.btnid).on("click", _obj.event);
         });
     }

	/*
		var valueDiv = document.createElement( 'div' );
		valueDiv.style.position = 'absolute';
		valueDiv.style.top = '0px';
		valueDiv.style.left = '0px';
		valueDiv.style.width = '500px';
		valueDiv.style.height = '300px';
		valueDiv.style.fontSize = '60px';
		container.append( valueDiv );
		valueNode = document.createTextNode( 'rrrr' );
		valueDiv.appendChild( valueNode );
	*/
 }

 /*
 *事件部分
 */

 //鼠标按下事件
 var dbclick =0;
 var vclickevent ='';
 p3D.prototype.onDocumentMouseDown = function (event) {
     dbclick++;
     var _this = p3DObj;
     setTimeout(function () {
			if (dbclick >= 2) vclickevent ='dbclick';
			else if (dbclick == 1) vclickevent ='click';
			else vclickevent ='';
			//console.log(dbclick+vclickevent);
			dbclick =0;

			_this.onEventDeal(vclickevent,event);

			}, 500);
     event.preventDefault();

 }

 p3D.prototype.onDocumentMouseMove = function (event) {
     event.preventDefault();
     var _this = p3DObj;
     _this.mouseClick.x = (event.clientX / _this.width) * 2 - 1;
     _this.mouseClick.y = -(event.clientY / _this.height) * 2 + 1;
     _this.raycaster.setFromCamera(_this.mouseClick, _this.camera);

 }

  p3D.prototype.onEventDeal = function (clickevent,emouse) {
	var _this = p3DObj;
	var imouse=emouse;
	if (clickevent=='')
			return ;

	//alert(imouse.x+"-"+imouse.y+"**"+_this.mouseClick.x+"-"+_this.mouseClick.y+"**");
	//console.log(clickevent);
	 _this.raycaster.setFromCamera(_this.mouseClick, _this.camera);
	 var intersects = _this.raycaster.intersectObjects(_this.objects);
	 if (intersects.length > 0) {
		 _this.controls.enabled = false;
		 _this.SELECTED = intersects[0].object;
		//alert(vclickevent);
		 if (clickevent=='dbclick') {

			  if (_this.eventList != null && _this.eventList.dbclick != null && _this.eventList.dbclick.length > 0) {
				 $.each(_this.eventList.dbclick, function (index, _obj) {
					 if ("string" == typeof (_obj.obj_name)) {
						 if (_obj.obj_name == _this.SELECTED.name) {
							 _obj.obj_event(_this.SELECTED,imouse);
						 }
					 } else if (_obj.findObject!=null||'function' == typeof (_obj.findObject)) {
						 if (_obj.findObject(_this.SELECTED.name)) {
							 _obj.obj_event(_this.SELECTED,imouse);
							 //alert(_this.SELECTED.name);
						 }
					 }
				 });
			 }

		 } else if (clickevent=='click') {

			if (_this.eventList != null && _this.eventList.mouseDown != null && _this.eventList.mouseDown.length > 0) {
				 $.each(_this.eventList.mouseDown, function (index, _obj) {
					 if ("string" == typeof (_obj.obj_name)) {
						 if (_obj.obj_name == _this.SELECTED.name) {
							 _obj.obj_event(_this.SELECTED,imouse);
						 }
					 } else if (_obj.findObject!=null||'function' == typeof (_obj.findObject)) {
						 if (_obj.findObject(_this.SELECTED.name)) {
							 _obj.obj_event(_this.SELECTED,imouse);
							 //alert(_this.SELECTED.name);
						 }
					 }
				 });
			 }

		 }

		 _this.controls.enabled = true;
	 }
  }
 p3D.prototype.addTunnel = function (objinfo,objitems) {
	  /*
	   {
		 name:'nurbs001',
		 type:'beeline',
		 visible:true,
		 scene:true,
		 radiu:1.0,
		 imgurl: '../textures/UV_Grid_Sm.jpg',
	   }
	 */
    var _this = p3DObj;
	var points = [];
	var path ;

	if (objitems != null && objitems.length > 0) {
		 $.each(objitems, function (index,_obj) {
			 var point=new THREE.Vector3( 0,0,0 );
			 point.x=_obj.x;
			 point.y=_obj.y;
			 point.z=_obj.z;
			 points.push( point );
		 });
	}

	if (objinfo.type == null || typeof (objinfo.type) == 'undefined' || objinfo.type == 'curve')  {
		path=new THREE.CatmullRomCurve3(points);
		//path=new THREE.LineCurve3(points[0],points[1]);
	}else if (objinfo.type == 'beeline') {
		function CustomSinCurve( scale ) {
			THREE.Curve.call( this );
			this.scale = ( scale === undefined ) ? 1 : scale;
		}
		CustomSinCurve.prototype = Object.create( THREE.Curve.prototype );
		CustomSinCurve.prototype.constructor = CustomSinCurve;
		CustomSinCurve.prototype.getPoint = function ( t ) {
			var vsegment=points.length-1;
			var vt=1/vsegment;
			vindex=parseInt(t/vt);
			if(1===t) {
				console.log(t+'/'+vt +' = '+vindex+' ');
				//vindex=points.length-1;//.multiplyScalar( this.scale )
				//return new THREE.Vector3( points[vindex].x, ps[vindex].y, ps[vindex].z );
				return points[vindex].clone();
			}
			//console.log(t+'/'+vt +' = '+vindex+' '+(vindex+1));

			var vector = new THREE.Vector3();
			vector.subVectors( points[vindex+1], points[vindex] ); // diff
			vector.multiplyScalar( (t-(vt*vindex))*vsegment );
			vector.add( points[vindex] );

			return vector;
		};
		path = new CustomSinCurve( 10 );
	}

	var map = new THREE.TextureLoader().load( objinfo.imgurl );
		map.wrapS = map.wrapT = THREE.RepeatWrapping;
		map.anisotropy = 16;
	var material = new THREE.MeshLambertMaterial( { map: map, side: THREE.DoubleSide } );
	_this.vcmaterial=material;
	//_this.vcmaterial.map.offset.x += 1;

	var geometry = new THREE.TubeGeometry( path, 750, objinfo.radiu, 8, false );
	//var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
	var mesh = new THREE.Mesh( geometry, material );
	mesh.position.set( 0, 0, 0 );
	mesh.name=objinfo.name;
	mesh.visible=objinfo.visible;

	if(true==objinfo.scene)
		_this.addObject(mesh);
	return mesh;
 }
 p3D.prototype.addLine = function (objinfo,objitems) {
	  /*
	   {
		 name:'nurbs001',
		 type:'',
		 position:{x:0,y:0,z:0},
		 size:{x:20,y:20},
		 colortype:'gradient',
		 color:0xffffff,
		 imgurl: '../mng/arrow.png',
	   }
	 */
    var _this = p3DObj;
	var geometry3 = new THREE.Geometry();
	var colors3 = [];
	if (objitems != null && objitems.length > 0) {
		 $.each(objitems, function (index,_obj) {
			 var point=new THREE.Vector3( 0,0,0 );
			 point.x=_obj.x;
			 point.y=_obj.y;
			 point.z=_obj.z;
			 geometry3.vertices.push( point );

			 if('gradient'==objinfo.colortype) {
				colors3[ index ] = new THREE.Color( objinfo.color );
				colors3[ index ].setHSL( index / objitems.length, 1.0, 0.5 );
			 }
		 });
	}
	var vParams={ color: objinfo.color, opacity: 1, linewidth: 1 };
	if('gradient'==objinfo.colortype) {
		geometry3.colors = colors3;
		vParams={ color: objinfo.color, opacity: 1, linewidth: 1, vertexColors: THREE.VertexColors };
	}

	var material = new THREE.LineBasicMaterial( vParams );
	var line, p, scale = 1.0, d = 225;
	line = new THREE.Line(geometry3, material );
	line.scale.x = line.scale.y = line.scale.z =  scale*1.0;
	line.position.x = objinfo.position.x;
	line.position.y = objinfo.position.y;
	line.position.z = objinfo.position.z;
	line.name=objinfo.name;

	console.log( line.name );
	_this.addObject(line);
 }
 p3D.prototype.addNurbs = function (objinfo,objitems) {
	  /*
	   {
		 name:'nurbs001',
		 type:'nurbs',
		 position:{x:0,y:100,z:0},
		 size:{x:20,y:20},
		 color:{r:255, g:255, b:255, a:1.0},
		 imgurl: '../mng/arrow.png',
	   }
	 */
    var _this = p3DObj;

	var nsControlPoints = [];
	var vx=0,vy=0,vz=0;
	var vstepx=300,vstepy=40,vstepz=50;
	for ( var i = 0; i < 3; i ++ ) {
		var v1=	[
					new THREE.Vector4 ( vx+(i*vstepx), vy-5*vstepy, vz+3.5*vstepz, 1 ),
					new THREE.Vector4 ( vx+(i*vstepx), vy-2.8*vstepy, vz+2.0*vstepz, 1 ),
					new THREE.Vector4 ( vx+(i*vstepx), vy-2.5*vstepy, vz+0.0*vstepz, 1 ),
					new THREE.Vector4 ( vx+(i*vstepx), vy-0*vstepy, vz-0.9*vstepz, 1 )
				];
		nsControlPoints.push(v1);
	}

	var degree1 = 2;
	var degree2 = 3;
	var knots1 = [0, 0, 0, 1, 1, 1];
	var knots2 = [0, 0, 0, 0, 1, 1, 1, 1];
	var nurbsSurface = new THREE.NURBSSurface(degree1, degree2, knots1, knots2, nsControlPoints);

	var map = new THREE.TextureLoader().load( objinfo.imgurl );
	map.wrapS = map.wrapT = THREE.RepeatWrapping;
	map.anisotropy = 16;
	map.repeat.set( 8, 6 );
	map.needsUpdate = true;

	// function getSurfacePoint(u, v) {
	// 	return nurbsSurface.getPoint(u, v);
	// }
   function getSurfacePoint( u, v, target ) {
     return nurbsSurface.getPoint( u, v, target );
   }

	var geometry = new THREE.ParametricBufferGeometry( getSurfacePoint, 20, 20 );

	//
	geometry.computeVertexNormals();
	geometry.normalizeNormals();
	var lutColors = [];
	var vColors = [
					{r: 0, g: 0.5, b: 0.7},
					{r: 0.6, g: 1.0, b: 0.3},
					{r: 0.1, g: 0.9, b: 0.1},
				  ];
	for ( var i = 0; i < geometry.attributes.normal.array.length; i++ ) {

		var color = vColors[ i%3 ];
		if ( color == undefined ) {
			console.log( "ERROR: " + colorValue );
		} else {
			lutColors[ 3 * i     ] = color.r;
			lutColors[ 3 * i + 1 ] = color.g;
			lutColors[ 3 * i + 2 ] = color.b;
		}
	}
	geometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( lutColors ), 3 ) );
	//

	var material = new THREE.MeshLambertMaterial( { map: map, side: THREE.DoubleSide, opacity: 0.8, transparent: true,vertexColors: THREE.VertexColors } );
	var object = new THREE.Mesh( geometry, material );
	object.position.set( objinfo.position.x, objinfo.position.y, objinfo.position.z );
	object.rotation.y=55;
	object.name=objinfo.name;
	//object.rotateY(90);
	object.scale.multiplyScalar( 1 );
	_this.nurbsmaterial=material;

	_this.addObject(object);
 }
  p3D.prototype.addSprite = function (objinfo) {
	  /*
	   {
		 name:'nurbs001',
		 type:'nurbs',
		 position:{x:0,y:100,z:0},
		 size:{x:20,y:20,z:20},
		 color:{r:255, g:255, b:255, a:1.0},
		 imgurl: '../mng/arrow.png',
	   }
	 */
    var _this = p3DObj;

	var particle;
	var vscale=objinfo.position.w;
	var spriteMap = new THREE.TextureLoader().load( objinfo.imgurl );
	var material = new THREE.SpriteMaterial( {
		map: spriteMap,
		color: objinfo.color,
		blending: THREE.AdditiveBlending
	} );
	for ( var i = 0; i < objinfo.number; i++ ) {

		particle = new THREE.Sprite( material );
		//particle.position.set( 0, 0, 0 );
		_this.initParticle( objinfo, particle, i * 10, vscale );
		particle.name=objinfo.name;

		_this.addObject( particle );
	}

 }
 p3D.prototype.initParticle = function ( objinfo, particle, delay, scale ) {
	var _this = p3DObj;
	//var particle = this instanceof THREE.Sprite ? this : particle;
	//var delay = delay !== undefined ? delay : 0;

	if (particle == null || typeof (particle) == 'undefined')
		return ;
	particle.position.set( objinfo.position.x, objinfo.position.y, objinfo.position.z );
	particle.scale.x = particle.scale.y = Math.random() * scale + scale*2;

	var vMinx=objinfo.position.x;
	var vMaxx=objinfo.position.x+objinfo.size.x;
	var vMiny=objinfo.position.y;
	var vMaxy=objinfo.position.y+objinfo.size.y;
	var vMinz=objinfo.position.z;
	var vMaxz=objinfo.position.z+objinfo.size.z;

	new TWEEN.Tween( particle )
		.delay( delay )
		.to( {}, 1000 )
		.onComplete( function () { _this.initParticle(objinfo, particle, delay, scale); } )
		.start();

	new TWEEN.Tween( particle.position )
		.delay( delay )
		.to( { x: (Math.random()*(vMaxx-vMinx+1)+vMinx), y: (Math.random()*(vMiny-vMaxy+1)+vMiny), z: (Math.random()*(vMaxz-vMinz+1)+vMinz) }, 10000 )
		.start();

	new TWEEN.Tween( particle.scale )
		.delay( delay )
		.to( { x: 0.01, y: 0.01 }, 10000 )
		.start();
}

 //创建
 p3D.prototype.addPlane = function (_objinfo) {
	/*
	{
		name:'',
	    width:0,
	    height:0,
	    pic:"",
	    transparent:true,
	    opacity:1
	    blending:false,
		color:{r:255, g:255, b:255, a:1.0},
		position: { x:,y:,z:},
		rotation: { x:,y:,z:},
	}
	*/
	var _this = p3DObj;
    var  options = _objinfo;
     if (typeof options.pic == "string") {//传入的材质是图片路径，使用 textureloader加载图片作为材质
         var loader = new THREE.TextureLoader();
         loader.setCrossOrigin(this.crossOrigin);
         var texture = loader.load(options.pic, function () { }, undefined, function () { });
     } else {
         var texture = new THREE.CanvasTexture(options.pic)
     }
     var MaterParam = {//材质的参数
         map: texture,
         side: THREE.DoubleSide,
         //blending: THREE.AdditiveBlending,
         transparent: options.transparent,
         //needsUpdate:true,
         //premultipliedAlpha: true,
         opacity: options.opacity
     }
     if (options.blending) {
         MaterParam.blending = THREE.AdditiveBlending//使用饱和度叠加渲染
     }
     var plane = new THREE.Mesh(
         new THREE.PlaneGeometry(options.width, options.height, 1, 1),
         new THREE.MeshBasicMaterial(MaterParam)
     );

	var lutColors = [];
	var vColors = [
					{r: 0, g: 0.5, b: 0.7},
					{r: 0.6, g: 1.0, b: 0.3},
					{r: 0.1, g: 0.9, b: 0.1},
				  ];
	for ( var i = 0; i < 100; i++ ) {

		var color = vColors[ i%3 ];
		if ( color == undefined ) {
			console.log( "ERROR: " + colorValue );
		} else {
			lutColors[ 3 * i     ] = color.r;
			lutColors[ 3 * i + 1 ] = color.g;
			lutColors[ 3 * i + 2 ] = color.b;
		}
	}
	plane.geometry.colors=lutColors;

     plane.position.x = options.position.x;
     plane.position.y = options.position.y;
     plane.position.z = options.position.z;
     plane.rotation.x = _this.AngleToRadians(options.rotation.x);
     plane.rotation.y = _this.AngleToRadians(options.rotation.y);
     plane.rotation.z = _this.AngleToRadians(options.rotation.z);
     plane.name=options.name;
	 _this.addObject( plane );
 }

  //创建box
 p3D.prototype.addBox = function (_objinfo) {
	/*
	{
		name:'',
	    transparent:true,
	    opacity:0.5,
	    blending:false,
		wireframe:false,
		tween:1800,
		color:0xffffff,
		size: { x:,y:,z:},
		position: { x:,y:,z:},
		rotation: { x:,y:,z:},
	}
	*/
	var _this = p3DObj;
	var vheight = _objinfo.size.h;
	if( _objinfo.tween>0 ) {
		vheight = 1;
	}
	var geometry = new THREE.BoxGeometry( _objinfo.size.w, vheight, _objinfo.size.l );
	//var geometry = new THREE.BoxGeometry( 100, 50, 50 );
	var object = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: _objinfo.color, opacity: _objinfo.opacity,transparent: _objinfo.transparent,wireframe: _objinfo.wireframe ,shininess: 100} ) );

	object.name=_objinfo.name;
	object.position.set(_objinfo.position.x,_objinfo.position.y,_objinfo.position.z);
	object.rotation.set(_objinfo.rotation.x,_objinfo.rotation.y,_objinfo.rotation.z);
	if(true==_objinfo.wireframe) {
		var bh = new THREE.BoxHelper(object,_objinfo.color);
		bh.name=_objinfo.name;
		_this.addObject( bh );
	} else {
	 _this.addObject( object );
	}

	if( _objinfo.tween>0 ) {
		var vsize=_objinfo.size;
		var vtheight=vheight;
		new TWEEN.Tween( { h : vheight } ).to( {
				h: vsize.h }, _objinfo.tween )
			.onUpdate(function() {
				//console.log(this.h);
				//object.geometry.dispose();
				//object.children[ 1 ].geometry.dispose();
				var vtgeometry = new THREE.BoxGeometry( vsize.w, this.h, vsize.l );
				//object.children[ 0 ].geometry = new THREE.WireframeGeometry( vtgeometry );
				object.geometry = vtgeometry;
				var v1=(this.h-vtheight)/2.0;
				object.position.y+=v1;
				vtheight=this.h;
			}).easing(TWEEN.Easing.Elastic.Out).start();
	}

 }

 p3D.prototype.delSenceObject = function (_objname,_deltype) {
	var _this = p3DObj;
	_this.delObject(_objname,_deltype);
 }

  p3D.prototype.dynamicPath = function (dpathinfo,dpathposition) {
	 var _this = p3DObj;
	 var vv=_this.addTunnel(dpathinfo,dpathposition);
	 this.pathTubeGeometry=vv.geometry;
	 this.dynamicPathTimer=0.0;
  }
  p3D.prototype.stopDynamicPath = function (dynamicPathName) {
	 var _this = p3DObj;
	 this.pathTubeGeometry=null;
	 this.dynamicPathTimer=0.0;
	 this.delSenceObject(dynamicPathName);
  }

  p3D.prototype.AngleToRadians  = function (vAngle) {
	  return Math.PI/180*vAngle;
  }
  p3D.prototype.RadiansToAngle  = function (vRadians) {
	  return 180/Math.PI*vRadians;
  }

 p3D.prototype.addTestObj = function () {

     var _this = p3DObj;

     var jsloader = new THREE.JSONLoader();
     if(false) {
     jsloader.load("pressure.json",
         function (geometry, materials) {
             var model = new THREE.SkinnedMesh(geometry, materials);
             model.name = 'test';
             model.scale.x = 10;
             model.scale.y = 7;
             model.scale.z = 10;
             model.position.x = -300;
             model.position.y = 50;
             model.position.z = 300;
             _this.addObject(model);
         });
     } else {
     jsloader.load("models/bh/BH_ARCH_B1.json",
         function (geometry, materials) {
             var material = new THREE.MeshFaceMaterial(materials);

             var mesh = new THREE.Mesh(geometry, materials);

             // Turn on shadows
             mesh.castShadow = true;

             //mesh.scale.set(0.25, 0.25, 0.25);
             mesh.position.set(-300,50,300);
             _this.addObject(mesh);
         });
     }

     //var plane =
     //_this.createPlaneGeometry(_this, {
     //    width: 100,
     //    height: 200,
     //    pic: "../datacenterdemo/mng/glass.png",
     //    transparent: true,
     //    opacity: 1,
     //    position: { x: 0, y: 100, z: -200 },
     //    rotation: { x: 0, y: 0*Math.PI, z: 0 },
     //    blending: false
     //});
 }
